package com.dgut.smart_house.shiro;

import com.dgut.smart_house.domain.User;
import com.dgut.smart_house.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    //授权逻辑
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        System.out.println("授权逻辑");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        User dbUser = userService.findByUserId(user.getUserId());
        String perms = dbUser.getPerms();
        String permslist[] = perms.split(",");
        for (String perm : permslist)
            info.addStringPermission(perm);
        return info;

    }

    //认证逻辑
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User user = userService.findByUserId(token.getUsername());
        if (user == null) {
            return null;//底层抛出UnknownAccountException
        }
        ByteSource salut = ByteSource.Util.bytes(user.getSalt());//获取加密盐值
        return new SimpleAuthenticationInfo(user, user.getPassword(), salut, "");
    }
}